let process = require('child_process')
let command = 'adb '
export default {
  exec : function(str,devicesId){
    if(str && devicesId){
      command = command + '-s ' + devicesId + ' ' + str
      process.exec(command,function(error,stdout, stderr){
        return stdout
      })
    }
  },
  getDevicesId: function () {
    let newStdout = []
    let deviceArr = []
    let valueTemp = ''
    let valueTemp2 = ''
    let deviceNumberArr = []
    let item = {
      index: '',
      device: ''
    }
    process.exec('adb devices', function (error, stdout, stderr) {
        if (!error) {
          newStdout = stdout.split('\n')
          deviceArr = newStdout.slice(1, -1)
          if (deviceArr.length > 0) {
            let testValue = deviceArr[0].replace(/[\r\n]*/g, '')
            if (testValue !== '') {
              deviceArr.forEach((value, index) => {
                valueTemp2 = value.replace(/[\r\n]*/g, '')
                if (valueTemp2 !== '') {
                  valueTemp = valueTemp2.split('\t')
                  item.index = index
                  item.device = valueTemp[0]
                  deviceNumberArr.push(item)
                }
              })
            }
          }
        }else{
          return []
        }
      }
    )
  },
  devices: function () {
    process.exec('adb devices', function (error, stdout, stderr) {
      if (error) {
        return false
      } else {
        return stdout
      }
    })
  },
  tcpip: async function (port,deviceId) {
    let com = command

    if(parseInt(port) && deviceId){
      let result = false
      com = com + '-s ' + deviceId + ' tcpip ' + port
      await process.exec(com, function (error, stdout, stderr) {
        console.log(stdout)
        result =  stdout.indexOf('restarting') !== -1;
        console.log(result)
      })
      return result
    }
  },
  connect : function (ip,port){
    let com = command+'connect ';
    if(port){
      com = com + ip + ':' + parseInt(port)
    }else{
      com = com + ip
    }
    console.log(com)
    process.exec(com,function (error, stdout, stderr) {
      console.log(stdout)
      if (error) {
        return false
      } else {

        return stdout
      }
    })
  },
  killServer : function (){
    process.exec('adb kill-server')
  },
  startServer : function (){
    process.exec('adb start-server')
  },
  version : function () {
    process.exec('adb version')
  },
  installApp : function(){

  },

}
